package com.tencent.wxcloudrun.service.business.zuke;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tencent.wxcloudrun.config.CustomException;
import com.tencent.wxcloudrun.config.UserContext;
import com.tencent.wxcloudrun.dao.XHouseCollectMapper;
import com.tencent.wxcloudrun.pojo.bo.HouseStatusEnum;
import com.tencent.wxcloudrun.pojo.bo.MediaInfo;
import com.tencent.wxcloudrun.pojo.dto.resp.UdIdToListResp;
import com.tencent.wxcloudrun.pojo.po.XHouseCollect;
import com.tencent.wxcloudrun.pojo.po.XHouseInfo;
import com.tencent.wxcloudrun.pojo.po.XHouseTag;
import com.tencent.wxcloudrun.service.XHouseCollectService;
import com.tencent.wxcloudrun.service.XHouseInfoService;
import com.tencent.wxcloudrun.service.XHouseTagService;
import com.tencent.wxcloudrun.service.business.fangdong.HouseManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HouseCollectService {
    @Resource
    private XHouseCollectMapper xHouseCollectMapper;

    @Resource
    private XHouseInfoService xHouseInfoService;

    @Resource
    private XHouseTagService xHouseTagService;

    @Resource
    private XHouseCollectService xHouseCollectService;

    @Transactional(rollbackFor = Exception.class)
    public String addHouseCollect(String houseId) {
        LambdaQueryWrapper<XHouseInfo> xHouseInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHouseInfoLambdaQueryWrapper.eq(XHouseInfo::getHouseId, houseId);
        XHouseInfo houseInfo = xHouseInfoService.getOne(xHouseInfoLambdaQueryWrapper);
        // 未认证的房屋不能被收藏
        if (!"yes".equals(houseInfo.getPicAuth())) {
            throw new CustomException("未认证的房屋不能被收藏");
        }
        String openId = UserContext.getOpenId();
        XHouseCollect xHouseCollect = new XHouseCollect();
        Date date = new Date();
        xHouseCollect.setTenantId(openId);
        xHouseCollect.setHouseId(houseId);
        xHouseCollect.setCreateTime(date);
        xHouseCollect.setUpdateTime(date);
        xHouseCollectService.save(xHouseCollect);
        return "收藏成功";
    }

    @Transactional(rollbackFor = Exception.class)
    public String delHouseCollect(String houseId) {
        String openId = UserContext.getOpenId();
        LambdaQueryWrapper<XHouseCollect> xHouseCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHouseCollectLambdaQueryWrapper.eq(XHouseCollect::getHouseId, houseId);
        xHouseCollectLambdaQueryWrapper.eq(XHouseCollect::getTenantId, openId);
        xHouseCollectMapper.delete(xHouseCollectLambdaQueryWrapper);
        return "已取消收藏";
    }

    public XHouseCollect getHouseCollect(String houseId) {
        String openId = UserContext.getOpenId();
        LambdaQueryWrapper<XHouseCollect> xHouseCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHouseCollectLambdaQueryWrapper.eq(XHouseCollect::getHouseId, houseId);
        xHouseCollectLambdaQueryWrapper.eq(XHouseCollect::getTenantId, openId);
        return xHouseCollectService.getOne(xHouseCollectLambdaQueryWrapper);
    }

    public List<UdIdToListResp> getAllHouseCollectResp() {
        String openId = UserContext.getOpenId();
        if (openId == null) {
            log.warn("openId is null, user may not be logged in.");
            return Collections.emptyList();
        }
        LambdaQueryWrapper<XHouseCollect> xHouseCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHouseCollectLambdaQueryWrapper.eq(XHouseCollect::getTenantId, openId);
        List<XHouseCollect> collect = xHouseCollectService.list(xHouseCollectLambdaQueryWrapper);
        if (collect == null || collect.isEmpty()) {
            log.info("No collected houses found for openId: {}", openId);
            return Collections.emptyList();
        }
        List<UdIdToListResp> respList = new ArrayList<>();
        for (XHouseCollect houseCollect : collect) {
            LambdaQueryWrapper<XHouseInfo> xHouseInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xHouseInfoLambdaQueryWrapper.eq(XHouseInfo::getHouseId, houseCollect.getHouseId());
            XHouseInfo xHouseInfo = xHouseInfoService.getOne(xHouseInfoLambdaQueryWrapper);
            if (xHouseInfo == null) {
                log.warn("No house info found for houseId: {}", houseCollect.getHouseId());
                continue;
            }
            UdIdToListResp udIdToListResp = new UdIdToListResp();
            // 拼接房源信息字符串（带 null 检查）
            String houseName = xHouseInfo.getHouseName() != null ? xHouseInfo.getHouseName() : "未知房源";
            String floor = xHouseInfo.getFloor() != null ? xHouseInfo.getFloor() + "楼" : "未知楼层";
            String mouthMoney = (xHouseInfo.getMouthMoney() != null) ? xHouseInfo.getMouthMoney().toPlainString() + "元" : "价格未知";
            udIdToListResp.setHouseInfo(houseName + "_" + floor + "_" + mouthMoney);
            // 获取标签（注意：之前写的是 openId，其实应该是 houseId）
            LambdaQueryWrapper<XHouseTag> xHouseTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
            xHouseTagLambdaQueryWrapper.eq(XHouseTag::getHouseId, xHouseInfo.getHouseId());
            List<XHouseTag> allByHouseId = xHouseTagService.list(xHouseTagLambdaQueryWrapper);
            if (allByHouseId != null) {
                List<String> tagList = allByHouseId.stream()
                        .map(XHouseTag::getTagId)
                        .filter(Objects::nonNull)
                        .limit(4)
                        .collect(Collectors.toList());
                udIdToListResp.setTagList(StrUtil.join("、", tagList));
            }
            // 房屋状态
            if (xHouseInfo.getHouseState() != null) {
                HouseStatusEnum statusEnum = HouseStatusEnum.findByValue(xHouseInfo.getHouseState());
                if (statusEnum != null) {
                    udIdToListResp.setHouseStatus(statusEnum.getKey());
                } else {
                    log.warn("Unknown house state: {}", xHouseInfo.getHouseState());
                }
            }
            // 图片处理
            if (xHouseInfo.getPicId() != null) {
                try {
                    List<MediaInfo> mediaInfoList = JSON.parseArray(xHouseInfo.getPicId(), MediaInfo.class);
                    if (mediaInfoList != null) {
                        List<MediaInfo> picCol = mediaInfoList.stream()
                                .filter(var -> {
                                    String suffix = HouseManageService.getLastPartAfterDot(var.getFileID());
                                    return "jpeg".equalsIgnoreCase(suffix) ||
                                            "jpg".equalsIgnoreCase(suffix) ||
                                            "png".equalsIgnoreCase(suffix);
                                })
                                .collect(Collectors.toList());

                        if (!picCol.isEmpty()) {
                            udIdToListResp.setPic(picCol.get(0).getFileID());
                        }
                    }
                } catch (Exception e) {
                    log.error("Error parsing picId JSON for houseId: {}", xHouseInfo.getHouseId(), e);
                }
            }
            // 设置索引（houseId）
            udIdToListResp.setIndex(xHouseInfo.getHouseId());
            // 加入返回列表
            respList.add(udIdToListResp);
        }

        return respList;
    }

}
